package cn.demoncat.pay.service.impl;

import cn.demoncat.pay.constant.CebConstant;
import cn.demoncat.pay.mapper.CebMemberMapper;
import cn.demoncat.pay.pojo.CebMember;
import cn.demoncat.pay.pojo.CebMemberAccount;
import cn.demoncat.pay.pojo.CebMemberBankLog;
import cn.demoncat.pay.pojo.CebMemberLog;
import cn.demoncat.pay.service.CebMemberAccountService;
import cn.demoncat.pay.service.CebMemberBankLogService;
import cn.demoncat.pay.service.CebMemberLogService;
import cn.demoncat.pay.service.CebMemberService;
import cn.demoncat.user.constant.UserConstant;
import cn.demoncat.user.pojo.UserInfo;
import cn.demoncat.user.util.OrgUtil;
import cn.demoncat.user.util.UserUtil;
import cn.demoncat.util.exception.AuthRuntimeException;
import cn.demoncat.util.exception.BizErrorRuntimeException;
import cn.demoncat.util.exception.ParamRuntimeException;
import cn.demoncat.util.lang.*;
import cn.demoncat.util.lang.constant.FundDirection;
import cn.demoncat.util.lang.constant.StatusConstant;
import cn.demoncat.util.lang.constant.StringConstant;
import cn.demoncat.util.lang.entity.Pager;
import cn.demoncat.util.lang.entity.Result;
import cn.demoncat.util.lang.entity.SidName;
import cn.demoncat.util.mybatis.plus.Query;
import cn.demoncat.util.mybatis.plus.base.BaseServiceImpl;
import cn.demoncat.util.pay.ceb.CebUtil;
import cn.demoncat.util.pay.ceb.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/** 
 * 光大-会员账户接口实现类
 *
 * @author 延晓磊
 *
 * @since 2022-02-24
 */
@Service
public class CebMemberServiceImpl extends BaseServiceImpl<CebMemberMapper, CebMember> implements CebMemberService {

    @Resource
    private CebUtil cebUtil;
    @Resource
    private UserUtil userUtil;
    @Resource
    private OrgUtil orgUtil;
    @Resource
    private CebMemberAccountService cebMemberAccountService;
    @Resource
    private CebMemberLogService cebMemberLogService;
    @Resource
    private CebMemberBankLogService cebMemberBankLogService;

    private static final Logger LOG = LoggerFactory.getLogger(CebMemberServiceImpl.class);

    /**
     * 查询银行及行号（总行）
     *
     * @param cardNo
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public SidName getBankCode(String cardNo){
        QueryBankResponseParam.ResponseBody result = cebUtil.queryBank(StringUtil.checkBlank(cardNo));
        if (result != null) {
            return new SidName(result.getJointLineNm(), result.getBankname());
        }
        return null;
    }

    /**
     * 获取付款信息
     *
     * @param id
     * @return null = 未开通账户不能付款
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public FundInfo getFundInfo(Long id){
        CebMember member = this.getById(id);
        if (member == null) {
            return null;
        }else{
            return cebUtil.fundInfo(member.getMemNum());
        }
    }

    /**
     * 查询余额+可用余额
     *
     * @param id    供应商ID，空表示平台
     * @param memNum 会员编号（非空时忽略供应商ID）
     * @return {balance，useableBalance}
     *
     * @throws NullPointerException 会员账户不存在
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public AmountResponseParam.ResponseBody getBalances(Long id, String memNum){
        if (StringUtils.isNotBlank(memNum)) {
            // 企业余额
            return cebUtil.queryAccountBalance("99", memNum, null);
        }else{
            if (LongUtil.isEmpty(id)) {
                // 平台余额
                return cebUtil.queryAccountBalance("0", null, null);
            }else{
                // 企业余额
                return cebUtil.queryAccountBalance("99", this.getById(id).getMemNum(), null);
            }
        }
    }

    /**
     * 查询可用余额
     *
     * @param id    供应商ID，空表示平台
     * @param memNum 会员编号（非空时忽略供应商ID）
     * @return 可用余额，null表示会员账户不存在
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public BigDecimal getUseBalance(Long id, String memNum) {
        try {
            return getBalances(id,memNum).getUseableBalance();
        }catch (NullPointerException e){
           return null;
        }
    }

    /**
     * 获取平台余额
     *
     * @return {'0':汇总，'1':收入，'2':利息}
     *
     * @author 延晓磊
     * @since 2022年03月01日
     */
    @Override
    public Map<String,AmountResponseParam.ResponseBody> getPlatformBalances(){
        Map<String,AmountResponseParam.ResponseBody> map = new HashMap<>();
        map.put("1", cebUtil.queryAccountBalance("0", null, null));
        map.put("2", cebUtil.queryAccountBalance("1", null, null));
        map.put("3", cebUtil.queryAccountBalance("2", null, null));
        return map;
    }

    /**
     * 查询会员详情
     *
     * @param id        供应商ID
     * @param memNum    会员编码（优先于id）
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public MemberQueryResponseParam.ResponseBody getMemberInfo(Long id, String memNum){
        if (StringUtils.isNotBlank(memNum)) {
            return cebUtil.queryMember(memNum, null);
        }else if (!LongUtil.isEmpty(id)) {
            return cebUtil.queryMember(null, id.toString());
        }
        throw ParamRuntimeException.NULL;
    }

    /**
     * 查询会员资金明细
     * 
     * @param id    供应商ID
     * @param mark  类型：0全部，2入金，1出金，3交易明细
     * @param pageNum   页号
     * @param pageSize  页长，最大99条
     * @param startDate 起始日
     * @param endDate   结束日，相距小于3个月
     * @return {list,totalCount}
     * 
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public Pager<QueryAccountLogResponseParam.ResponseBody.Data> findLogList(Long id, String mark, Integer pageNum, Integer pageSize, String startDate, String endDate){
        // 查询会员
        CebMember member = this.getById(id);
        if (member == null) {
            throw new BizErrorRuntimeException("账户未开通");
        }
        // 查询列表
        Pager<QueryAccountLogResponseParam.ResponseBody.Data> page = cebUtil.queryAccountLogPage(member.getMemNum(), mark, "99", pageNum, pageSize, startDate, endDate, false, false);
        if (!page.getList().isEmpty()) {
            // 映射摘要
            page.getList().parallelStream().forEach(o -> {
                if (QueryAccountLogResponseParam.ResponseBody.Data.BizType.TRADE.equals(o.getBusType())) {
                    // 交易，冻结解冻的摘要为日志ID
                    if (StringUtils.isNumeric(o.getBrief())) {
                        CebMemberLog log = cebMemberLogService.getById(Integer.valueOf(o.getBrief()));
                        if (log != null) {
                            o.setBrief(log.getPid() + (StatusConstant.Common.isYes(o.getAddReduce()) ? "-余额解冻" : "-余额冻结"));
                        }
                    }
                }
            });
        }
        return page;
    }

    /**
     * 查询平台资金明细
     *
     * @param type    账户类型：0-虚拟汇总户(默认)、1-虚拟收入户、2-虚拟利息户、3-支付调节户、5-资金暂挂户、7-自有资金回补户
     * @param mark  类型：0全部，2入金，1出金，4资金暂挂
     * @param pageNum   页号
     * @param pageSize  页长，最大99条
     * @param startDate 起始日
     * @param endDate   结束日，相距小于3个月
     * @return {list,totalCount}
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public Pager<QueryAccountLogResponseParam.ResponseBody.Data> findLogList(String type, String mark, Integer pageNum, Integer pageSize, String startDate, String endDate){
        return cebUtil.queryAccountLogPage(null, mark, StringUtil.toDefault(type, "0"), pageNum, pageSize, startDate, endDate, false, false);
    }

    /**
     * 查询会员提现明细
     *
     * @param id    供应商ID
     * @param pageNum   页号
     * @param pageSize  页长，最大99条
     * @param startDate 起始日
     * @param endDate   结束日
     * @return {list,totalCount}
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public Pager<QueryTakeResponseParam.ResponseBody.Data> findLogList(Long id, Integer pageNum, Integer pageSize, String startDate, String endDate){
        // 查询会员
        CebMember member = this.getById(id);
        if (member == null) {
            throw new BizErrorRuntimeException("账户未开通");
        }
        // 查询列表
        return cebUtil.queryTakePage(null, null, member.getMemNum(), startDate, endDate, pageNum, pageSize);
    }

    /**
     * 冻结：将企业账户的冻结额解冻，然后再重新冻结可用余额
     *
     * 场景：投标、修改
     *
     * @param id    供应商ID
     * @param sid   投标ID
     * @param pid   招标编号
     * @param amount    投标金额
     * @return 成功 {status:200}，失败 {status:400,msg:错误消息,data: 1冻结失败，2解冻失败，12解冻成功后冻结失败，null其它问题}
     *
     * @author 延晓磊
     * @since 2022年02月28日
     */
    @Override
    public Result freeze(Long id, Long sid, String pid, BigDecimal amount){
        // 参数校验
        if (id == null || sid == null || amount == null) {
            return Result.ERROR_PARAM_NULL;
        }
        // 查询账户
        CebMember member = this.getById(id);
        if (member == null) {
            return Result.error("您还没有开通资金账户");
        }
        // 查询上次交易
        CebMemberLog last = cebMemberLogService.getFirst(new Query<CebMemberLog>().eq("mem_id", id).eq("sid", sid).descId());
        if (last == null || !last.getType().equals(CebConstant.MemberLogType.FREEZE)) {
            // 首次冻结
            if (DecimalUtil.isEq(amount)) {
                // 资金为0，忽略
                return Result.SUCCESS;
            }
            CebMemberLog log = new CebMemberLog();
            log.setAmount(amount);
            log.setMemId(id);
            log.setSid(sid);
            log.setType(CebConstant.MemberLogType.FREEZE);
            log.setCreateTime(LocalDateTime.now());
            cebMemberLogService.save(log);
            // 远程冻结
            try {
               cebUtil.freeze(member.getMemNum(), log.getId().toString(), StatusConstant.Common.NO, amount, null);
            }catch (Exception e){
                // 冻结失败
                cebMemberLogService.delete(log.getId());
                LOG.warn("请求光大银行-冻结资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
                return Result.error(e.getMessage(), CebConstant.MemberLogType.FREEZE);
            }
        }else{
            // 解冻
            CebMemberLog log = new CebMemberLog();
            log.setAmount(last.getAmount());
            log.setMemId(id);
            log.setSid(sid);
            log.setPid(pid);
            log.setType(CebConstant.MemberLogType.UNFREEZE);
            log.setCreateTime(LocalDateTime.now());
            cebMemberLogService.save(log);
            // 远程解冻
            try {
                cebUtil.freeze(member.getMemNum(), log.getId().toString(), StatusConstant.Common.YES,  log.getAmount(), last.getId().toString());
            }catch (Exception e){
                // 解冻失败
                cebMemberLogService.delete(log.getId());
                LOG.warn("请求光大银行-解冻资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
                return Result.error(e.getMessage(), CebConstant.MemberLogType.UNFREEZE);
            }
            // 冻结
            if (DecimalUtil.isEq(amount)) {
                // 资金为0，忽略
                return Result.SUCCESS;
            }
            log = new CebMemberLog();
            log.setAmount(amount);
            log.setMemId(id);
            log.setSid(sid);
            log.setType(CebConstant.MemberLogType.FREEZE);
            log.setCreateTime(LocalDateTime.now());
            cebMemberLogService.save(log);
            // 远程冻结
            try {
                cebUtil.freeze(member.getMemNum(), log.getId().toString(), StatusConstant.Common.NO, amount, null);
            }catch (RuntimeException e){
                // 冻结失败
                cebMemberLogService.delete(log.getId());
                LOG.warn("请求光大银行-冻结资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
                return Result.error(e.getMessage(), CebConstant.MemberLogType.UNFREEZE + CebConstant.MemberLogType.FREEZE);
            }
        }
        return Result.SUCCESS;
    }

    /**
     * 解冻：将企业账户冻结额解冻
     *
     * 场景：取消投标、未中标
     *
     * @param id    供应商ID
     * @param sid   投标ID
     * @param pid   招标编号
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    @Override
    public Result unfreeze(Long id, Long sid, String pid){
        // 参数校验
        if (id == null || sid == null) {
            return Result.ERROR_PARAM_NULL;
        }
        // 查询上次交易
        CebMemberLog last = cebMemberLogService.getFirst(new Query<CebMemberLog>().eq("mem_id", id).eq("sid", sid).descId());
        if (last == null || !last.getType().equals(CebConstant.MemberLogType.FREEZE)) {
            // 未冻结，忽略
            return Result.SUCCESS;
        }
        // 查询账户
        CebMember member = this.getById(id);
        if (member == null) {
            return Result.error("未查询到资金账户");
        }
        // 解冻
        CebMemberLog log = new CebMemberLog();
        log.setAmount(last.getAmount());
        log.setMemId(id);
        log.setSid(sid);
        log.setPid(pid);
        log.setType(CebConstant.MemberLogType.UNFREEZE);
        log.setCreateTime(LocalDateTime.now());
        cebMemberLogService.save(log);
        // 远程解冻
        try {
            cebUtil.freeze(member.getMemNum(), log.getId().toString(), StatusConstant.Common.YES,  log.getAmount(), last.getId().toString());
        }catch (Exception e){
            // 解冻失败
            cebMemberLogService.delete(log.getId());
            LOG.warn("请求光大银行-解冻资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
            return Result.error(e.getMessage(), CebConstant.MemberLogType.UNFREEZE);
        }
        return Result.SUCCESS;
    }

    /**
     * 收取：将企业账户的冻结额解冻，然后划转到平台账户
     *
     * 场景：定标收取
     *
     * @param id    供应商ID
     * @param sid   投标ID
     * @param pid   招标编号
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月28日
     */
    @Override
    public Result charge(Long id, Long sid, String pid){
        // 参数校验
        if (id == null || sid == null) {
            return Result.ERROR_PARAM_NULL;
        }
        // 查询上次交易
        CebMemberLog last = cebMemberLogService.getFirst(new Query<CebMemberLog>().eq("mem_id", id).eq("sid", sid).descId());
        if (last == null || !last.getType().equals(CebConstant.MemberLogType.FREEZE)) {
            // 未冻结，忽略
            return Result.SUCCESS;
        }
        // 查询账户
        CebMember member = this.getById(id);
        if (member == null) {
            return Result.error("未查询到资金账户");
        }
        // 收取
        CebMemberLog log = new CebMemberLog();
        log.setAmount(last.getAmount());
        log.setMemId(id);
        log.setSid(sid);
        log.setPid(pid);
        log.setType(CebConstant.MemberLogType.FINISH);
        log.setCreateTime(LocalDateTime.now());
        cebMemberLogService.save(log);
        // 远程收取
        try {
            cebUtil.pay(log.getId().toString(), sid.toString(), member.getMemNum(), log.getAmount(), null, last.getId().toString(), pid + "-服务费收取", null);
        }catch (Exception e){
            // 解冻失败
            cebMemberLogService.delete(log.getId());
            LOG.warn("请求光大银行-收取资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
            return Result.error(e.getMessage(), CebConstant.MemberLogType.FINISH);
        }
        return Result.SUCCESS;
    }

    /**
     * 退款：将平台账户的可用余额，划转到企业账户
     *
     * 场景：退票（操作后需要再冻结-收取）
     *
     * @param id    供应商ID
     * @param sid   投标ID
     * @param pid   招标编号
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月28日
     */
    @Override
    public Result refund(Long id, Long sid, String pid){
        // 参数校验
        if (id == null || sid == null) {
            return Result.ERROR_PARAM_NULL;
        }
        // 查询上次交易
        CebMemberLog last = cebMemberLogService.getFirst(new Query<CebMemberLog>().eq("mem_id", id).eq("sid", sid).descId());
        if (last == null || !last.getType().equals(CebConstant.MemberLogType.FINISH)) {
            // 未收取，忽略
            return Result.SUCCESS;
        }
        // 查询账户
        CebMember member = this.getById(id);
        if (member == null) {
            return Result.error("未查询到资金账户");
        }
        // 退款
        CebMemberLog log = new CebMemberLog();
        log.setAmount(last.getAmount());
        log.setMemId(id);
        log.setSid(sid);
        log.setPid(pid);
        log.setType(CebConstant.MemberLogType.REFUND);
        log.setCreateTime(LocalDateTime.now());
        cebMemberLogService.save(log);
        // 远程退款
        try {
            cebUtil.pay(log.getId().toString(), sid.toString(), null, log.getAmount(), member.getMemNum(), last.getId().toString(), pid + "-退票退款", null);
        }catch (Exception e){
            // 退款失败
            cebMemberLogService.delete(log.getId());
            LOG.warn("请求光大银行-退还资金失败：id = {}, sid = {}, amount = {}", id, sid, log.getAmount(), e);
            return Result.error(e.getMessage(), CebConstant.MemberLogType.REFUND);
        }
        return Result.SUCCESS;
    }

    /**
     * 提现：企业将余额提出到银行卡
     *
     * @param id		实体账户ID
     * @param amount
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月28日
     */
    @Transactional
    @Override
    public Result take(String id, BigDecimal amount) {
        // 参数校验
        if (amount == null || StringUtils.isBlank(id)) {
            return Result.ERROR_PARAM_NULL;
        }
        if (DecimalUtil.isLe(amount)) {
            return Result.error("提现金额必须大于0");
        }
        // 用户校验
        UserInfo user = checkUser();
        CebMember member = this.getById(user.getOrgId());
        if (member == null) {
            return Result.error("您还没有开通资金账户");
        }
        // 账户校验
        CebMemberAccount account = cebMemberAccountService.getById(id);
        if (account == null || !account.getMemId().equals(member.getId())) {
            return Result.error("银行实体账户未绑定");
        }
        // 提现
        CebMemberBankLog log = new CebMemberBankLog();
        log.setMemId(member.getId());
        log.setCardNum(account.getId());
        log.setCardName(member.getMemName());
        log.setBankNum(account.getBankNum());
        log.setBankName(account.getBankName());
        log.setSubBankName(account.getSubBankName());
        log.setTradeId(StringConstant.EMPTY);
        log.setTradeDate(LocalDateUtil.toDateStr());
        log.setTradeDirection(FundDirection.EXPEND);
        log.setAmount(amount);
        log.setRemarks(StringConstant.EMPTY);
        log.setStatus(StatusConstant.Handle.INIT);
        log.setCreateTime(LocalDateTime.now());
        log.setUpdateTime(log.getCreateTime());
        cebMemberBankLogService.save(log);
        // 请求远程
        log.setTradeId(cebUtil.take(member.getMemNum(), "B" + log.getId(), amount, log.getBankNum(), log.getCardName(), log.getCardNum(), CebConstant.MemberAccountBankType.TAKE_MAP.get(account.getBankType()), user.getName() + "-大宗交易网提现").getBody().getFcsSerialNum());
        cebMemberBankLogService.update(log);
        return Result.SUCCESS;
    }

    /**
     * 转出余额：平台将余额提出到银行卡
     *
     * @param type 操作类型：1-收入资金划转、2-利息收入划转
     * @param amount 转出金额，为该type下的相应余额
     *
     * @return
     *
     * @author 延晓磊
     * @since 2022年02月28日
     */
    @Override
    public Result settle(String type, BigDecimal amount) {
        cebUtil.settle(StatusConstant.Common.isYes(type) ? "2":"4", IDUtil.getSnowflakeId(), amount, LocalDateTime.now(),  userUtil.get().getName() + "-大宗交易网转出");
        return Result.SUCCESS;
    }

    /**
     * 供应商申请开通账户
     *
     * @param data
     * @return
     *
     * @author 延晓磊
     *
     * @since 2022-02-24
     */
    @Transactional
    @Override
    public Result add(CebMember data) {
        // 参数校验
        ParamEmptyUtil.checkBlank(data.getLegalName(), data.getLegalIdCard());
        // 用户校验
        UserInfo user = checkUser();
        // 账户校验
        if (this.exists(user.getOrgId())) {
            return Result.error("您已开通账户");
        }
        data.setId(user.getOrgId());
        data.setUscc(user.getSupplier().getUscc());
        data.setMemName(user.getSupplier().getName());
        // 开通账户
        MemberManageRequestParam param = MemberManageRequestParam.buildSave();
        param.setMemName(data.getMemName());
        param.setRegisName(data.getId().toString());
        param.setIdentiNum(data.getUscc());
        param.setLegalName(data.getLegalName());
        param.setLegalIdCard(data.getLegalIdCard());
        data.setMemNum(cebUtil.manageMember(param).getBody().getMemNum());
        // 保存账户
        data.setCreateTime(LocalDateTime.now());
        data.setUpdateTime(data.getCreateTime());
        this.save(data);
        return Result.success(data);
    }

    /**
     * 供应商添加银行实体账户
     *
     * @param data
     * @return
     *
     * @author 延晓磊
     *
     * @since 2022-02-24
     */
    @Transactional
    @Override
    public Result addAccount(CebMemberAccount data) {
        // 参数校验
        ParamEmptyUtil.checkBlank(data.getId(), data.getBankNum(), data.getBankName(), data.getSubBankName());
        // 用户校验
        UserInfo user = checkUser();
        // 账户校验
        CebMember member = this.getById(user.getOrgId());
        if (member == null) {
            return Result.error("您还没有开通账户");
        }
        if (cebMemberAccountService.exists(data.getId())) {
            return Result.error("银行账户已存在");
        }
        // 添加账户
        if (data.getBankName().startsWith(CebUtil.BANK_NAME)) {
            data.setBankType(CebConstant.MemberAccountBankType.INSIDE);
        }else if (CebConstant.BANK_MAP.containsKey(data.getBankNum())) {
            data.setBankType(CebConstant.MemberAccountBankType.OUTSIDE_BIG);
        }else{
            data.setBankType(CebConstant.MemberAccountBankType.OUTSIDE_SMALL);
        }
        MemberManageRequestParam param = MemberManageRequestParam.buildUpdate(member.getMemNum());
        param.setMemName(member.getMemName());
        param.setRegisName(member.getId().toString());
        param.setIdentiNum(member.getUscc());
        param.setLegalName(member.getLegalName());
        param.setLegalIdCard(member.getLegalIdCard());
        MemberManageRequestParam.Account account = MemberManageRequestParam.Account.buildSave();
        account.setBindOpenBank(data.getBankName());
        account.setBindOpenOrgNum(data.getBankNum());
        account.setBindOpenBankName(data.getSubBankName());
        account.setBindAccNum(data.getId());
        account.setBindAccName(member.getMemName());
        cebUtil.manageMember(param.addAccount(account));
        // 保存账户
        data.setMemId(member.getId());
        data.setCreateTime(LocalDateTime.now());
        data.setUpdateTime(data.getCreateTime());
        cebMemberAccountService.save(data);
        return Result.success(data);
    }

    /**
     * 供应商删除银行实体账户
     *
     * @param id
     * @return
     *
     * @author 延晓磊
     *
     * @since 2022-02-24
     */
    @Transactional
    @Override
    public Result delAccount(String id) {
        return cebMemberAccountService.handle(id, dbData ->{
            // 用户校验
            UserInfo user = checkUser();
            if (!dbData.getMemId().equals(user.getOrgId())) {
                return Result.ERROR_AUTH;
            }
            // 账户校验
            CebMember member = this.getById(user.getOrgId());
            if (member == null) {
                return Result.error("您还没有开通账户");
            }
            // 删除账户
            MemberManageRequestParam param = MemberManageRequestParam.buildUpdate(member.getMemNum());
            param.setMemName(member.getMemName());
            param.setRegisName(member.getId().toString());
            param.setIdentiNum(member.getUscc());
            param.setLegalName(member.getLegalName());
            param.setLegalIdCard(member.getLegalIdCard());
            MemberManageRequestParam.Account account = MemberManageRequestParam.Account.buildDelete();
            account.setBindOpenBank(dbData.getBankName());
            account.setBindOpenOrgNum(dbData.getBankNum());
            account.setBindOpenBankName(dbData.getSubBankName());
            account.setBindAccNum(dbData.getId());
            account.setBindAccName(member.getMemName());
            cebUtil.manageMember(param.addAccount(account));
            // 删除
            cebMemberAccountService.delete(id);
            return Result.SUCCESS;
        });
    }



    /**
     * 用户校验
     *
     * @return user
     *
     * @author 延晓磊
     * @since 2022年02月24日
     */
    private UserInfo checkUser(){
        // 用户校验
        UserInfo user = userUtil.get();
        if (!UserConstant.Type.SUPPLIER.equals(user.getType()) || !UserConstant.Status.ENABLE.equals(user.getStatus()) || StatusConstant.Common.isNo(user.getIsAdmin())) {
            throw AuthRuntimeException.NULL;
        }
        // 企业校验
        user.setSupplier(orgUtil.getSupplier(user.getOrgId()));
        if (StatusConstant.Common.isNo(user.getSupplier().getStatus()) || !StatusConstant.Common.isYes(user.getSupplier().getAuditStatus())) {
            throw AuthRuntimeException.NULL;
        }
        return user;
    }


}